package com.blockchain.front.servlets.trading;

import java.io.IOException;
import java.math.BigDecimal;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.blockchain.common.enums.JyztStatus;
import com.blockchain.framework.resource.PromptLevel;
import com.blockchain.framework.service.ServiceSession;
import com.blockchain.framework.service.exception.LogicalException;
import com.blockchain.framework.service.exception.ParameterException;
import com.blockchain.front.service.trading.TradingManage;
import com.blockchain.util.parser.BigDecimalParser;
import com.blockchain.util.parser.EnumParser;
import com.blockchain.util.parser.IntegerParser;

public class Trading extends AbstractTradingServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void processPost(HttpServletRequest request, HttpServletResponse response, ServiceSession serviceSession)
			throws Throwable {
		
		JyztStatus type = EnumParser.parse(JyztStatus.class, request.getParameter("type"));
		int scid = IntegerParser.parse(request.getParameter("scid"));
		BigDecimal price = BigDecimalParser.parse(request.getParameter("price"));
		BigDecimal num = BigDecimalParser.parse(request.getParameter("num"));
		String password = request.getParameter("pwtrade");
		TradingManage tradingManage = serviceSession.getService(TradingManage.class);
		if (type != null && type == JyztStatus.MR) {
			tradingManage.tradingMr(scid, price, num, password);
		}
		if (type != null && type == JyztStatus.MC) {
			tradingManage.tradingMc(scid, price, num, password);
		}
		String url=getController().getViewURI(request,index.class)+"?id="+scid;
		sendRedirect(request, response,url);
	}
	@Override
	protected void onThrowable(HttpServletRequest request,
			HttpServletResponse response, Throwable throwable)
			throws ServletException, IOException {
		getResourceProvider().log(throwable.getMessage());
		int scid = IntegerParser.parse(request.getParameter("scid"));
		String url=getController().getViewURI(request,index.class)+"?id="+scid;
		if (throwable instanceof LogicalException
				|| throwable instanceof ParameterException) {
			prompt(request, response, PromptLevel.ERROR, throwable.getMessage());
			sendRedirect(request, response,url);
		}  else {
			super.onThrowable(request, response, throwable);
		}
	}
}
